package com.spx.library.player

import android.annotation.TargetApi
import android.content.Context
import android.content.pm.ActivityInfo
import android.media.MediaPlayer
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.RelativeLayout


class VideoPlayerOfMediaPlayer(val surfaceView: SurfaceView) : VideoPlayer {


    var mediaPlayer: MediaPlayer? = null
    var surfaceHolder: SurfaceHolder? = null
    var screenWidth: Int = 0
    var screenHeight: Int = 0


    override fun setupPlayer(context: Context, mediaPath: String) {
        var dm = context.resources.displayMetrics
        screenWidth = dm.widthPixels // 屏幕宽（像素，如：480px）
        screenHeight = dm.heightPixels // 屏幕高（像素，如：800px）
        mediaPlayer?.setDataSource(mediaPath)
        mediaPlayer?.prepare()
        mediaPlayer?.setOnPreparedListener {
            mediaPlayer!!.start()
            mediaPlayer!!.isLooping = true
        }
        mediaPlayer!!.setOnVideoSizeChangedListener{ mp, width, height->
            var videoWidth = mp.videoWidth
            var videoHeight = mp.videoHeight
            var  max :Float ?=null
            if (context.resources.configuration.orientation== ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                //竖屏模式下按视频宽度计算放大倍数值
                max = Math.max(videoWidth.toFloat() / screenWidth.toFloat(), videoHeight.toFloat() / screenHeight.toFloat())
            } else{
                //横屏模式下按视频高度计算放大倍数值
                max = Math.max((videoWidth.toFloat() / screenHeight.toFloat()), videoHeight.toFloat() / screenWidth.toFloat())
            }

            //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
            videoWidth = Math.ceil((videoWidth / max).toDouble()).toInt()
            videoHeight =  Math.ceil((videoHeight / max).toDouble()).toInt()

            val lay=RelativeLayout.LayoutParams(videoWidth, videoHeight)
            //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
            lay.addRule(RelativeLayout.CENTER_IN_PARENT)
            surfaceView.setLayoutParams(lay)
        }
    }

    override fun initPlayer() {
        mediaPlayer = MediaPlayer()
        val holder = surfaceView.holder
        if (surfaceHolder != null) {
            mediaPlayer!!.setDisplay(surfaceHolder)
        }
        holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
                mediaPlayer!!.setDisplay(holder)
                surfaceHolder = holder
            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {
            }

            override fun surfaceCreated(holder: SurfaceHolder?) {
            }

        })

    }

    override fun pausePlayer() {
        mediaPlayer?.pause()
    }

    override fun startPlayer() {
        mediaPlayer?.start()
    }

    override fun seekToPosition(position: Long) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mediaPlayer?.seekTo(position, MediaPlayer.SEEK_CLOSEST)
        } else {
            mediaPlayer?.seekTo(position.toInt())
        }
    }

    override fun getPlayerCurrentPosition(): Int {
        return mediaPlayer?.currentPosition ?: 0
    }

    override fun setPlaySpeed(speed: Float) {
        setMediaPlayerSpeed(speed)
    }

    @TargetApi(Build.VERSION_CODES.M)
    private fun setMediaPlayerSpeed(speed: Float) {
        if (mediaPlayer!!.isPlaying()) {
            mediaPlayer!!.setPlaybackParams(mediaPlayer!!.getPlaybackParams().setSpeed(speed))
            mediaPlayer!!.start()
        } else {
            mediaPlayer!!.setPlaybackParams(mediaPlayer!!.getPlaybackParams().setSpeed(speed))
            mediaPlayer!!.pause()
        }
    }

    override fun enableFramePreviewMode() {

    }

    override fun releasePlayer() {
        mediaPlayer?.stop()
        mediaPlayer?.reset()
    }

    override fun isPlaying(): Boolean {
        return mediaPlayer?.isPlaying ?: false
    }
    override fun getDuration(): Int {
        return mediaPlayer?.duration?:0
    }
}